package com.situ.onlinebookstore.front.controller.api;

import com.situ.onlinebookstore.common.entity.Order;
import com.situ.onlinebookstore.common.entity.User;
import com.situ.onlinebookstore.common.vo.Pay;
import com.situ.onlinebookstore.common.vo.Result;
import com.situ.onlinebookstore.front.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/user/order")
@RequiredArgsConstructor
public class OrderApiController {
    private final OrderService orderService;

    //创建订单
    @PostMapping
    public Result create(@RequestBody Order order, HttpSession session) {
        User user = (User) session.getAttribute("user");
        order.setUserId(user.getId());
        try {
            orderService.create(order);
            return Result.ok(order.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    //根据ID获取订单
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") String id, HttpSession session) {
        /*
        处理器方法的参数注解
        @RequestParam   :解决前后端参数不一致
        @DateTimeFormat :解决Date类型自动注入
        @PathVariable   :绑定路径参数
        @RequestBody    :接收JSON格式的参数
         */
        User user = (User) session.getAttribute("user");
        try {
            Order order = orderService.getById(id, user.getId());
            return Result.ok(order);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @GetMapping
    public Result get(Integer page, Integer limit, Order order, HttpSession session) {
        User user = (User) session.getAttribute("user");
        order.setUserId(user.getId());
        return Result.ok(orderService.searchForPage(page,limit,order));
    }

    //支付订单
    @PutMapping("/pay")
    public Result pay(@RequestBody Pay pay, HttpSession session) {
        User user = (User) session.getAttribute("user");
        try {
            orderService.pay(pay.getOrderId(), pay.getPayPassword(), user.getId());
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }

    }
}
